package com.kun.common.service;

import com.kun.common.util.JsonUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisService {

    private final StringRedisTemplate stringRedisTemplate;

    public RedisService(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void setKey(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value, 1, TimeUnit.HOURS);
    }

    public void setKey(String key, Object value) {
        stringRedisTemplate.opsForValue().set(key, JsonUtils.toJson(value), 1, TimeUnit.HOURS);
    }

    public void setKey(String key, String value, long timeout, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    public String getKey(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    // 延长key的过期时间
    public void expireKey(String key, long timeout, TimeUnit unit) {
        stringRedisTemplate.expire(key, timeout, unit);
    }

    /**
     * 获取key的过期时间
     */
    public Long getExpire(String key, TimeUnit unit) {
        return stringRedisTemplate.getExpire(key, unit);
    }

    /**
     * 删除key
     */
    public void delKey(String key) {
        stringRedisTemplate.delete(key);
    }
}
